/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2020. All rights reserved.
 */

package com.huawei.chengdu.meetingdemo.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @since 2021/03/09
 * 使用ScheduledExecutorService替代Timer
 */
public class RelTimer {
    private ScheduledExecutorService pool;

    private final List<ScheduledFuture<?>> futures = new ArrayList<>();

    public RelTimer() {
    }

    /**
     * 开启任务
     *
     * @param task   任务
     * @param delay  延迟
     * @param period 期间
     */
    public void schedule(Runnable task, long delay, long period) {
        if (pool == null) {
            pool = new ScheduledThreadPoolExecutor(1);
        }
        ScheduledFuture<?> future = pool.scheduleAtFixedRate(task, delay, period, TimeUnit.MILLISECONDS);
        futures.add(future);
    }

    /**
     * 开启任务
     *
     * @param task  任务
     * @param delay 延迟
     */
    public void schedule(Runnable task, long delay) {
        if (pool == null) {
            pool = new ScheduledThreadPoolExecutor(1);
        }
        pool.schedule(task, delay, TimeUnit.MILLISECONDS);
    }

    /**
     * 取消任务
     */
    public void cancel() {
        if (pool == null) {
            return;
        }
        futures.forEach(it -> it.cancel(true));
        pool.shutdownNow();
        pool = null;
    }
}
